package com.chenjiagou.flight.service;

import com.chenjiagou.flight.model.Flight;
import com.chenjiagou.flight.model.FlightSeat;
import com.chenjiagou.flight.repository.AirportRepository;
import com.chenjiagou.flight.repository.FlightRepository;
import com.chenjiagou.flight.repository.FlightSeatRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class FlightService {

    @Autowired
    private FlightRepository flightRepository;

    @Autowired
    private AirportRepository airportRepository;

    @Autowired
    private FlightSeatRepository flightSeatRepository;

    // 获取所有机场名称（已修改为从数据库中查询 name 字段）
    public List<String> getAllAirportNames() {
        return airportRepository.findDistinctNamesOrderedByCode();
    }

    public Page<Flight> getAllFlights(Pageable pageable) {
        return flightRepository.findAll(pageable);
    }

    public Optional<Flight> getFlightById(Long id) {
        return flightRepository.findById(id);
    }

    public void addFlight(Flight flight) {
        flightRepository.save(flight);
    }

    public void deleteFlight(Long id) {
        flightRepository.deleteById(id);
    }

    /**
     * 根据航班ID生成座位记录
     *
     * @param flightId 航班ID
     */
    public void generateSeatsForFlight(Long flightId) {
        List<FlightSeat> seats = new ArrayList<>();

        for (int i = 1; i <= 30; i++) {
            FlightSeat seat = new FlightSeat();
            seat.setFlightId(flightId);
            seat.setSeatNo(String.valueOf(i));
            seat.setStatus(0); // 默认状态为可售

            if (i >= 1 && i <= 10) {
                seat.setSeatClassId(1L);
            } else if (i >= 11 && i <= 20) {
                seat.setSeatClassId(2L);
            } else {
                seat.setSeatClassId(3L);
            }

            seats.add(seat);
        }

        flightSeatRepository.saveAll(seats);
    }

    /**
     * 添加航班时生成座位记录
     *
     * @param flight 航班信息
     */
    public void addFlightWithSeats(Flight flight) {
        flightRepository.save(flight);
        generateSeatsForFlight(flight.getId());
    }

    // 根据出发机场和到达机场查询航班
    public List<Flight> searchFlights(String depAirport, String arrAirport) {
        if (depAirport != null && arrAirport != null) {
            return flightRepository.findByDepAirportAndArrAirport(depAirport, arrAirport);
        } else if (depAirport != null) {
            return flightRepository.findByDepAirport(depAirport);
        } else if (arrAirport != null) {
            return flightRepository.findByArrAirport(arrAirport);
        } else {
            return flightRepository.findAll();
        }
    }

    // 修改更新方法
    public void updateFlight(Flight flight) {
        flightRepository.save(flight);
    }
}